package cn.janyd.jmall.web.core.util;

import cn.janyd.jmall.web.core.constants.WebConstants;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * @author janyd
 * @since 2020/8/5 22:03
 */
public class WebUtil {


    public static void setAccessStartTime(ServletRequest request, long startTime) {
        request.setAttribute(WebConstants.REQUEST_ATTR_ACCESS_START_TIME, startTime);
    }

    public static long getAccessStartTime(ServletRequest request) {
        return (long) request.getAttribute(WebConstants.REQUEST_ATTR_ACCESS_START_TIME);
    }

    public static String getIp(HttpServletRequest request) {
        // 基于 X-Forwarded-For 获得
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个 ip 才是真实 ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        // 基于 X-Real-IP 获得
        ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        // 默认方式
        return request.getRemoteAddr();
    }
}
